import dict from '../core/dict';
import utils from '../core/utils';
import logger from '../core/logger';
import serviceCache from './serviceCache';
import common from '@ohos.app.ability.common';
import formItem from '../model/common/formItem';
import formProvider from '@ohos.app.form.formProvider';
import relationalStore from '@ohos.data.relationalStore';
import formBindingData from '@ohos.app.form.formBindingData';

export class serviceUntils {
  async createRdbStore(context: common.Context) {
    if (utils.isEmpty(globalThis.rdbStore)) {
      await relationalStore.getRdbStore(context, dict.STORE_CONFIG).then((rdbStore: relationalStore.RdbStore) => {
        if (!utils.isEmpty(rdbStore)) {
          rdbStore.executeSql(dict.CREATE_TABLE_FORM);
          globalThis.rdbStore = rdbStore;
        }
      });
    }
    return globalThis.rdbStore;
  }

  insertForm(form: formItem, rdbStore: relationalStore.RdbStore) {
    try {
      if ((utils.isEmpty(rdbStore)) || (utils.isEmpty(form)))
        return;
      rdbStore.insert(dict.TABLE_NAME, form.toValuesBucket());
    } catch (e) {
      logger.error(e);
    }
  }

  startTimer() {
    try {
      this.updateCardData(globalThis.rdbStore);
      if (utils.isEmpty(globalThis.intervalId)) {
        globalThis.intervalId = setInterval(() => {
          this.updateCardData(globalThis.rdbStore);
        }, dict.INTERVAL_DELAY_TIME);
      }
    } catch (e) {
      logger.error(e);
    }
  }

  updateCardData(rdbStore: relationalStore.RdbStore) {
    try {
      if (!utils.isEmpty(rdbStore)) {
        serviceCache.instance.getListData().then((listData) => {
          if (listData.length > 0) {
            serviceCache.instance.getFormData(listData).then((formData) => {
              let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.TABLE_NAME);
              rdbStore.query(predicates).then((resultSet: relationalStore.ResultSet) => {
                if (resultSet.rowCount > 0) {
                  resultSet.goToFirstRow();
                  do {
                    let formId: string = resultSet.getString(resultSet.getColumnIndex(dict.FORM_ID));
                    formProvider.updateForm(formId, formBindingData.createFormBindingData(formData))
                  } while (resultSet.goToNextRow());
                  resultSet.close();
                }
              });
            });
          }
        });
      }
    } catch (e) {
      logger.error(e);
    }
  }

  deleteFormData(formId: string, rdbStore: relationalStore.RdbStore) {
    try {
      if (!utils.isEmpty(rdbStore)) {
        let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.TABLE_NAME);
        predicates.equalTo(dict.FORM_ID, formId);
        rdbStore.delete(predicates);
      }
    } catch (e) {
      logger.error(e);
    }
  }
}
export default new serviceUntils();